package com.itruth.module.reg;

import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.itruth.base.BaseActivity;
import com.itruth.base.LocalNotice;
import com.itruth.base.NoticeCallback;
import com.itruth.data.entity.ResponseData;
import com.itruth.data.entity.UserData;
import com.itruth.main.R;
import com.itruth.module.main.MainActivity;
import com.itruth.util.Constant;
import com.itruth.util.HttpUtil;

public class RegActivity extends BaseActivity {
	
	private static final int ACCOUNT_EXIST = 0x01;
	
	private static final int REG_SUCCESS = 0x02;
	
	private EditText et_userName;
	
	private EditText et_password;
	
	@Override
	protected void initData() {
		
		LocalNotice.getIns().regNotice(LocalNotice.ACTION_REGISTER, receiver);
		
	}
	
	
	@Override
	protected void initComposition() {
		setContentView(R.layout.reg);
		
		Button regBtn = (Button)findViewById(R.id.btn_register);
		
		et_userName = (EditText) findViewById(R.id.et_username);
		et_password = (EditText) findViewById(R.id.et_password);
		
		regBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				HttpUtil.reg(et_userName.getText().toString().trim(),
						et_password.getText().toString().trim());
			}
		});
		
	}
	
	private Handler handler = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			
			switch(msg.what) {
				case ACCOUNT_EXIST:
					Toast.makeText(RegActivity.this, "账号已存在", Toast.LENGTH_SHORT).show();
					break;
				case REG_SUCCESS:
					Toast.makeText(RegActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
					UserData.getIns().setUserName(et_userName.getText().toString().trim());
					Intent intent = new Intent(RegActivity.this, MainActivity.class);
					startActivity(intent);
					break;
			}
			
		};
	};
	
	private NoticeCallback receiver = new NoticeCallback() {
		
		@Override
		public void callback(ResponseData data) {
			
			if (Constant.RESPONSE_OK == data.getStatus()) {
				
				if (Constant.RES_SUCCESS.equals(data.getProtocolTag())) {
					//注册成功
					handler.sendEmptyMessage(REG_SUCCESS);
					
				} else if (Constant.REG_ACCOUNT_EXIST.equals(data.getProtocolTag())) {
					//账号已存在
					handler.sendEmptyMessage(ACCOUNT_EXIST);
				}
				
			}
			
		}
	};
	
	protected void onDestroy() {
		LocalNotice.getIns().cancelNotice(LocalNotice.ACTION_REGISTER);
		super.onDestroy();
	};
	
}
